<template>
  <div class="coutom-echarts" ref="echartWrapRef" :style="{ width: width, height: height }">
    <div class="echart" ref="customEchart" style="width: 100%; height: 100%"></div>
    <CustomDialog v-model:dialogVisible="dialogVisible" :showFooter="false">
      <div>echar 详情</div>
    </CustomDialog>
  </div>
</template>

<script setup name="CustomEchart">
import { ref, reactive, onMounted, computed, onBeforeMount, nextTick, watch } from 'vue'
import { stores } from '@/stores/index.js'
import { mergeObj } from '@/utils/index.js'
import * as echarts from 'echarts'
const props = defineProps({
  offClick: {
    //关闭点击事件
    type: Boolean,
    default: true
  },
  width: {
    type: String,
    default: '500rem'
  },
  height: {
    type: String,
    default: '400rem'
  },

  type: {
    type: String,
    default: 'line'
  },
  option: {
    type: Object,
    default: () => {
      return {}
    }
  }
})

let echart = null
let baseOption = {}
const customEchart = ref()
const themeStore = stores.useThemeStore()
const resetTimer = ref(null)
const dialogVisible = ref(false)
const option = ref({})

watch(
  () => themeStore.themeColor,
  (newVal) => {
    // console.log(newVal)
    // echart && echart.dispose()
    // init()
    location.reload()
  },
  { deep: true }
)
watch(
  () => props.option,
  () => {
    option.value = mergeObj(baseOption, props.option)
    echart.setOption(option.value)
  },
  { deep: true }
)

onMounted(() => {
  init()
  addEventListener('resize', resize)
})
onBeforeMount(() => {
  removeEventListener('resize', resize)
  echart && echart.dispose()
  clearTimeout(resetTimer.value)
})

const init = async () => {
  echart = echarts.init(customEchart.value)
  baseOption = (await import(`./type/${props.type}.js`)).default.option
  //图表颜色跟随主题色
  if (props.type != 'pie') {
    baseOption.color = [themeStore.themeColor]
  }
  option.value = mergeObj(baseOption, props.option)

  echart.setOption(option.value)
  if (props.offClick) {
    echart.on('click', function (params) {
      console.log(params)
      dialogVisible.value = true
    })
  }
}
const resize = () => {
  clearTimeout(resetTimer.value)
  resetTimer.value = setTimeout(() => {
    echart.resize()
  }, 100)
}
</script>
<style lang="scss" scoped></style>
